package com.fengye.middleware.rabbitmq.boot.messageType.direct;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengye.middleware.rabbitmq.boot.messageType.EventInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 1:32 下午
 */
@Component
@Slf4j
public class DirectPublisher {

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.direct.exchange.name:direct_change_name}")
    private String directExchangeName;

    @Value("${mq.direct.routing.key.one.name:direct_routing_key_one_name}")
    private String directRoutingKeyOneName;

    @Value("${mq.direct.routing.key.two.name:direct_routing_key_two_name}")
    private String directRoutingKeyTwoName;

    public void sendObjectMsgOne(EventInfo info) {
        if (info != null) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(directExchangeName);
                rabbitTemplate.setRoutingKey(directRoutingKeyOneName);
                Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(info)).build();
                rabbitTemplate.convertAndSend(message);

                log.info("消息模型 DirectExchange：生产者-发送对象类型的消息：{}", info);
            } catch (Exception e) {
                log.error("消息模型 DirectExchange：生产者-发送消息异常：{}", info, e.fillInStackTrace());
            }
        }
    }





    public void sendObjectMsgTwo(EventInfo info) {
        if (info != null) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(directExchangeName);
                rabbitTemplate.setRoutingKey(directRoutingKeyTwoName);
                Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(info)).build();
                rabbitTemplate.convertAndSend(message);

                log.info("消息模型 DirectExchange：生产者-发送对象类型的消息：{}", info);
            } catch (Exception e) {
                log.error("消息模型 DirectExchange：生产者-发送消息异常：{}", info, e.fillInStackTrace());
            }
        }
    }
}
